<?php
class Run_Task
{
    public function run($params)
    {
        $method = 'run_' . $params[0];
        if (method_exists($this, $method)) {
            call_user_func(array($this, $method));
        }
    }

    private function run_sql()
    {
        $files = array(
            'structure.sql',
            'cities.sql',
            'anchors',
            'news.sql',
            'users.sql',
            'slides.sql',
            'settings.sql',

        );

        $dir = path('storage') .'database' . DS;

        DB::connection()->transaction(function () use($files, $dir) {
            foreach ($files as $file) {
                $this->exec_sql(file_get_contents($dir . $file));
            }
        });
    }

    private function exec_sql($sql_content)
    {
        $sql_stack = explode(';', $sql_content);
        foreach ($sql_stack as $sql) {
            $sql = trim($sql);

            if ($sql === '') continue;

            DB::query($sql);
        }
    }


    /**
     * Run task load tin tức từ rss
     * Đọc cấu hình từ application.rss đường dẫn file để ghi
     * application.rss_url đường dẫn tin tức
     */
    private function run_load_rss()
    {
        $rss_file = Config::get('application.rss');
        $rss_url = Config::get('application.rss_url');
        $parser = new Rss_Parser($rss_url);
        $counter = 0;

        $articles = array();
        $items = $parser->get_items();
        if (!is_null($items)) {
            foreach ($items as $item) {
                $parsed = filter_rss($item);
                if ($parsed) {
                    $articles[] = $parsed;
                    $counter++;
                }
            }
            echo "$counter records loaded!\n";
            File::put(path('storage') . 'cache/rss/' . $rss_file, json_encode($articles));
        }
    }

    /**
     * Gửi các email khôi phục mật khẩu
     */
    private function run_send_mail()
    {
        $log = "SEND MAIL\n";

        $users = User::where_email_sent(-1)->get();
        foreach ($users as $user) {
            $user->email_sent = 0;
            $user->verify_code = Str::random(10);

            $get = array(
                'secret' => $user->id,
                'code' => $user->verify_code,
            );

            $log .= "Sending to [{$user->username}] - {$user->email} ... ";
            $mail['subject'] = 'NhatroCT - Phục hồi mật khẩu';
            $mail['to_address'] = $user->email;
            $mail['to_name'] = $user->display_name;
            $mail['body'] = render('shared.emails.recover', array(
                'link' => 'user/recover?' . http_build_query($get),
                'username' => $user->username
            ));

            if (send_mail($mail) > 0) {
                $user->save();
                $log .= "sent!";
            }

            $log .= "\n";
        }
        echo $log;
    }


    private function run_test()
    {
        echo asset('/');
    }
}